'use strict'


let http = require('http');


let express = require('express');

let serveIndex = require('serve-index');



let app = express();


app.use(serveIndex('./dist'));
app.use(express.static('./dist'));


let http_server = http.createServer(app);
http_server.listen(3003);

let io = require('socket.io')(http_server, {
	path: '/rtcket'
});
http_server.on('listening', onListening);
function onListening() {
	let addr = http_server.address();
	let bind = typeof addr === 'string'
		? 'pipe ' + addr
		: 'port ' + addr.port;
	console.log('Listening on ' + bind,'addr=',addr);
}

let roomid = ''
let personListMap = {}
//connection
io.on('connection', (socket) => {

	socket.on('message', (room, data) => {
		console.log('接到的数据=', data)
		if (data === undefined) {
			return;
		}
		socket.to(room).emit('message', room, socket.id, data)

	});


	socket.on('join', (obj) => {
		let room = obj.room
		roomid = room
		socket.join(room);
		personListMap[socket.id] = obj

		let myRoom = io.sockets.adapter.rooms[room];
		let users = Object.keys(myRoom.sockets).length;

		if (users < 3) {
			socket.emit('joined', personListMap, socket.id);
			socket.to(room).emit('otherjoin', obj)

		} else {
			personListMap[socket.id] = null
			socket.leave(room);
			socket.emit('full', room, personListMap);
		}

	});

	socket.on('leave', (room) => {
		console.log(room);
		console.log('leave')
		let myRoom = io.sockets.adapter.rooms[room];


		personListMap[socket.id] = null
		socket.leave(room);
		socket.to(room).emit('bye', room, socket.id)
		socket.emit('leaved', room, socket.id);
	});

	socket.on('disconnect', function () {

		socket.to(roomid).emit('otherleave')
		socket.leave(roomid);
		personListMap[socket.id] = null
		console.log('disconnect')

	});
	socket.on('connect', function () {

		console.log('connect')

	});

});





